/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.activity;

import java.util.List;
import java.util.Map.Entry;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.SchedulesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopTimesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopsIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TaskIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TracksIntentHolder;
import lt.marsrutai.mobile.android.adapter.StopTimesTabInfoProvider;
import lt.marsrutai.mobile.android.adapter.TabAdapter;
import lt.marsrutai.mobile.android.fragment.StopTimesFragment;
import lt.marsrutai.mobile.android.fragment.task.GetStopArivalTimesTaskFragment;
import lt.marsrutai.mobile.android.fragment.task.TaskFragment;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.ArrivalTime;
import lt.marsrutai.mobile.android.model.DayGroup;
import lt.marsrutai.mobile.android.model.StopArrivalTimes;
import lt.marsrutai.mobile.android.model.enums.DateTime;
import lt.marsrutai.mobile.android.model.enums.WeekdayType;
import lt.marsrutai.mobile.android.task.GetStopArivalTimesTask;
import lt.marsrutai.mobile.android.task.GetTracksTask;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;

import com.viewpagerindicator.TabPageIndicator;

public class StopTimesActivity extends BaseActivity {
    
    private String GET_STOP_ARRIVAL_TIMES_TASK_FRAGMENT_TAG = "getStopArrivalTimes";

    private FragmentManager fragmentManager;
    private ActivityManager manager;
    
    private ViewPager viewPager;

    private StopArrivalTimes stopArrivalTimes;
    private String scopeFolder;
    private String scheduleId;
    private String trackId;
    private String stopId;
    
    /** Temp. variable. Used for saving currently active tab index */ 
    private int tabIndex = 0;

    private BroadcastReceiver stopArrivalTimesReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TaskIntentHolder holder = new TaskIntentHolder(intent);

            switch (holder.getStatus()) {
                case Activity.RESULT_OK:
                    stopArrivalTimes = holder.getResult();
                    
                    initialize();
                    manager.dismissDownloadLoadingBar();
                    break;
                case GetTracksTask.RESULT_NOT_RESOLVED:
                    manager.runOnUiThread(manager.errorRes);
                    break;
                default:
                    manager.dismissDownloadLoadingBar();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragmentManager = getSupportFragmentManager();
        manager = new ActivityManager(this);

        // Display loading in the temp view while the data is downloading
        setContentView(R.layout.progress_spinner);
        manager.showDownloadLoadingBar();

        restoreState(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(stopArrivalTimesReceiver, new IntentFilter(GetStopArivalTimesTask.BROADCAST_ACTION));

        if (stopArrivalTimes == null) {
            // Check whether the worker fragment has been retained
            TaskFragment<?, ?, ?> taskFragment = (TaskFragment<?, ?, ?>) fragmentManager.findFragmentByTag(GET_STOP_ARRIVAL_TIMES_TASK_FRAGMENT_TAG);
    
            // Start downloading only if we don't have any scopes, and task fragments has not been retained
            if (!TaskFragment.isActive(taskFragment)) {
                downloadData();
            }
        }
        else {
            // already have all the data - display it
            initialize();
            manager.dismissDownloadLoadingBar();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(stopArrivalTimesReceiver);
    }

    protected void downloadData() {
        TaskFragment.download(fragmentManager, 
                GetStopArivalTimesTaskFragment.class, GET_STOP_ARRIVAL_TIMES_TASK_FRAGMENT_TAG,
                new GetStopArivalTimesTask.Criteria[] { new GetStopArivalTimesTask.Criteria(scopeFolder, scheduleId, trackId, stopId) });
    }

    private void restoreState(Bundle bundle) {
        if (bundle == null) {
            bundle = getIntent().getExtras();
        }
        
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(bundle);
        scopeFolder = intentHolder.getScopeFolder();
        scheduleId = intentHolder.getScheduleId();
        trackId = intentHolder.getTrackId();
        stopId = intentHolder.getStopId();
        tabIndex = intentHolder.getTabIndex();
        stopArrivalTimes = intentHolder.getStopArrivalTimes();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(new Bundle());
        intentHolder.setScopeFolder(scopeFolder);
        intentHolder.setScheduleId(scheduleId);
        intentHolder.setTrackId(trackId);
        intentHolder.setStopId(stopId);
        intentHolder.setTabIndex(viewPager.getCurrentItem());
        intentHolder.setStopArrivalTimes(stopArrivalTimes);
        
        outState.putAll(intentHolder.getIntent().getExtras());
        
        super.onSaveInstanceState(outState);
    }
    

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        StopTimesIntentHolder sourceIntentHolder = new StopTimesIntentHolder(getIntent());

        switch (itemPosition) {
        case 1:
            StopsIntentHolder stopsintentHolder = new StopsIntentHolder(this,
                sourceIntentHolder.getScopeFolder(),
                sourceIntentHolder.getScopeName(),
                sourceIntentHolder.getTransportId(),
                sourceIntentHolder.getScheduleId(),
                sourceIntentHolder.getScheduleName(),
                sourceIntentHolder.getScheduleTrackName(),
                sourceIntentHolder.getTrackId(),
                sourceIntentHolder.getTrackName()
            );
            startActivity(stopsintentHolder.getIntent());
            break;
        case 2:
            TracksIntentHolder tracksintentHolder = new TracksIntentHolder(this,
                sourceIntentHolder.getScopeFolder(),
                sourceIntentHolder.getScopeName(),
                sourceIntentHolder.getTransportId(),
                sourceIntentHolder.getScheduleId(),
                sourceIntentHolder.getScheduleName(),
                sourceIntentHolder.getScheduleTrackName()
            );
            startActivity(tracksintentHolder.getIntent());
            break;
        case 3:
            SchedulesIntentHolder schedulesIntentHolder = new SchedulesIntentHolder(this);
            schedulesIntentHolder.setScopeFolder(sourceIntentHolder.getScopeFolder());
            schedulesIntentHolder.setScopeName(sourceIntentHolder.getScopeName());
            startActivity(schedulesIntentHolder.getIntent());
            break;
        case 4:
            startActivity(new Intent(this, ScopesActivity.class));
            break;
        default:
            return false;
        }

        return false;
    }

    @Override
    public NavMenuData getNavMenuData() {
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(getIntent());
        return new NavMenuData(new String[] {
                intentHolder.getStopName() + (intentHolder.getStopDirectionName() == null ? "" :  " (" + intentHolder.getStopDirectionName() + ")"),
                intentHolder.getTrackName(), 
                intentHolder.getScheduleTrackName(),
                intentHolder.getScopeName(), 
                getString(R.string.home) 
                },
                intentHolder.getScheduleName(), 2, intentHolder.getScopeFolder(), intentHolder.getTransportId());
    }

    private void initialize() {
        TabAdapter adapter = new TabAdapter(getSupportFragmentManager());
        WeekdayType today = WeekdayType.parseEnumSunSat(new DateTime().getWeekDay());
        int currentTabIndex = 0;
        int index = 0;

        for (Entry<DayGroup, List<ArrivalTime>> entry : stopArrivalTimes.getArrivalTimes()) {
            DayGroup dayGroup = entry.getKey();

            // Fill intent holder with proper info
            StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(getIntent().getExtras());
            intentHolder.setArrivalTimes(entry.getValue());

            // Add the tab
            adapter.addTab(new StopTimesTabInfoProvider(StopTimesFragment.class, intentHolder.getIntent().getExtras(), this, dayGroup));

            // Store the position of the current tab
            if (dayGroup.contains(today)) {
                currentTabIndex = index;
            }

            index++;
        }

        // Attach the adapted to the view pager
        setContentView(R.layout.tabs_viewpager_layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(adapter);

        // Attach view pager to tab page indicator
        TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
        indicator.setViewPager(viewPager);

        viewPager.setCurrentItem(tabIndex >= 0 ? tabIndex : currentTabIndex);
    }
}
